package com.demo.servlet.demo1216.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> local;

    static {
        try {
            //读取jdbc.properties属性配置文件
            Properties properties = new Properties();
            //输入流的获取
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //从输入流中加载数据
            properties.load(inputStream);
            //创建数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            //给当前线程 绑定连接对象
            local = new ThreadLocal<Connection>();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接池中的连接
     *
     * @return 如果返回null 说明获取连接失败 有值就是获取连接成功
     */
    public static Connection getConnection() {
        Connection connection = local.get();
        try {
            //如果是头一次调用 ，local.get() 是没有连接对象的
            if (connection == null){
                //从连接池拿到连接对象
                connection = dataSource.getConnection();
                //把连接保存到 ThreadLocal
                local.set(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接 放回数据库连接池
     *
     * @param connection
     */
    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
